<?php
/*********************************************************************************
 * This file is part of KReporter. KReporter is an enhancement developed 
 * by KINAMU Business Solutions AG. All rights ar (c) 2010 by KINAMU Business
 * Solutions AG.
 *
 * KReporter is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * KReporter is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with KReporter.  If not, see <http://www.gnu.org/licenses/>.
 * 
 * You can contact KINAMU Business Solutions AG at Am Concordepark 2/F12
 * A-2320 Schwechat or via email at office@kinamu.com
 * 
 * The interactive user interfaces in modified source and object code versions
 * of this program must display Appropriate Legal Notices, as required under
 * Section 5 of the GNU General Public License version 3.
 * 
 * In accordance with Section 7(b) of the GNU General Public License version 3,
 * these Appropriate Legal Notices must retain the Name KINAMU in the Name
 * of the Module which needs to be visible to the User.
 * 
 ********************************************************************************/
 require_once('include/MVC/Controller/SugarController.php');
 require_once('modules/Contacts/Contact.php');
 require_once('modules/KReports/utils.php');
  
 class KReportsController extends SugarController
{
	
	function action_get_modules(){
		global $app_list_strings;
		foreach($app_list_strings['moduleList'] as $module => $description)
		{
			$returnArray[] = array('module' => $module, 'description' => $description);
		}
		
		print json_encode_kinamu($returnArray);
	}
	
	
	function action_get_snapshots(){
		require_once('modules/KReports/KReport.php');
		
		$thisReport = new KReport();
		$thisReport->retrieve($_REQUEST['requester']);
		
		print json_encode_kinamu($thisReport->getSnapshots());
	}	
	
	
	function action_get_listfields(){
		require_once('modules/KReports/KReport.php');
		
		$thisReport = new KReport();
		$thisReport->retrieve($_REQUEST['record']);
		
		print json_encode_kinamu($thisReport->getListfields());
	}		
	
	
	
	function action_take_snapshot()
	{
		global $db;
		
		  require_once('modules/KReports/KReport.php');
		  require_once('include/utils.php');
		  $thisReport = new KReport();
		  $thisReport->retrieve($_REQUEST['record']);
		  
		  $snapshotID = create_guid();
		  
		  
		  $results = $thisReport->getSelectionResults(array('toPDF' => true, 'noFormat' => true));
		  $i = 0;
		  foreach($results as $resultsrow)
		  {
			  $query = 'INSERT INTO kreportsnapshotsdata SET record_id=\'' . $i . '\', snapshot_id = \'' . $snapshotID . '\', data=\'' . json_encode_kinamu($resultsrow) . '\'' ;
	    	  $db->query($query);
	    	  $i++;
		  }
		  
		  
		  $query = 'INSERT INTO kreportsnapshots SET id=\'' . $snapshotID . '\', snapshotdate =\'' . gmdate('Y-m-d H:i:s') . '\', report_id=\'' . $thisReport->id . '\'';
		  $db->query($query);
		  
		  return true;

	}
	

	function action_export_to_excel()
	{
	  global $current_user;
		
	  require_once('modules/KReports/KReport.php');
	  $thisReport = new KReport();
	  $thisReport->retrieve($_REQUEST['record']);
	  
	  
	  if(isset($_REQUEST['dynamicoptions']))
	  		  $thisReport->whereOverride = json_decode_kinamu( html_entity_decode_utf8($_REQUEST['dynamicoptions']));
	  
	  $results = $thisReport->getSelectionResults(array('noFormat' => true));
	
	  $arrayList =  json_decode_kinamu( html_entity_decode_utf8($thisReport->listfields));
	  
	  $fieldArray = '';
	  $fieldIdArray = array();
	  foreach($arrayList as $thisList){
	 	    if($thisList['display'] == 'yes')
	  	    {
				$fieldArray[] = array('label' => utf8_decode($thisList['name']), 'width' => (isset($thisList['width']) && $thisList['width'] != '' && $thisList['width'] != '0') ? $thisList['width'] : '100', 'display' => $thisList['display']);
				$fieldIdArray[] = $thisList['fieldid'];
	  	    }
	  }
	  
	  if(count($results > 0))
	  {
		  $header = '';
		  $rows = '';
		  
		  foreach($results as $record)
		  {
		  	$getHeader = ($header == '') ? true : false;
		  	foreach($record as $key => $value)
		  	{
		  		
			    $arrayIndex = array_search($key, $fieldIdArray);
			  	if(array_search($key, $fieldIdArray) !== false)		  			
		  		{
			  		if($getHeader) 
			  		{
			  			foreach($arrayList as $fieldId => $fieldArray)
			  				if($fieldArray['fieldid'] == $key) $header .= iconv("UTF-8", $current_user->getPreference('default_export_charset'), $fieldArray['name']) . $current_user->getPreference('export_delimiter');
			  		}
			  		$rows .= iconv("UTF-8", $current_user->getPreference('default_export_charset'), $value) . $current_user->getPreference(('export_delimiter')) ;

		  		}
		  	}
		  	if($getHeader) $header .= "\n";
		  	$rows .= "\n";
		  }
		  
	      $filename ="kinamureporter.csv";
	      header('Content-type: application/ms-excel');
	      header('Content-Disposition: attachment; filename='.$filename);
	      echo $header . $rows;
	  }
	}
	
	
	
	function action_export_to_targetlist()
	{
	  global $current_user; 
		
	  require_once('modules/KReports/KReport.php');
	  $thisReport = new KReport();
	  $thisReport->retrieve($_REQUEST['record']);
	  
	  
	  if(isset($_REQUEST['whereConditions']))
	  		  $thisReport->whereOverride = json_decode_kinamu( html_entity_decode_utf8($_REQUEST['whereConditions']));
	  
	  $results = $thisReport->getSelectionResults();
	
	  if(count($results > 0))
	  {
	  	require_once('modules/ProspectLists/ProspectList.php');
	  	$newProspectList = new ProspectList();
	  	
	  	$newProspectList->name = $_REQUEST['targetlist_name'];
	  	$newProspectList->list_type = 'default';
	  	$newProspectList->assigned_user_id = $current_user->id;
	  	$newProspectList->save();
	  	
	  	
	  	$newProspectList->load_relationships();
	  	
	  	$linkedFields = $newProspectList->get_linked_fields();
	  	
	  	foreach($linkedFields as $linkedField => $linkedFieldData)
	  	{
	  		if($newProspectList->$linkedField->_relationship->rhs_module == $thisReport->report_module)
	  		{
	  			
	  			foreach($results as $thisRecord)
	  			{
	  				 $newProspectList->$linkedField->add($thisRecord['sugarRecordId']);
	  			}
	  		}
	  	}
	  }
	  
	  return true;
	  
	}
	

	function action_check_export_to_targetlist()
	{
		
	  global $current_user; 
		
	  require_once('modules/KReports/KReport.php');
	  $thisReport = new KReport();
	  $thisReport->retrieve($_REQUEST['record']);
	  
	
	  	require_once('modules/ProspectLists/ProspectList.php');
	  	$newProspectList = new ProspectList();
	  	
	  	
	  	$newProspectList->load_relationships();
	  	
	  	$linkedFields = $newProspectList->get_linked_fields();
	  	
	  	$foundModule = false;
	  	
	  	foreach($linkedFields as $linkedField => $linkedFieldData)
	  	{
	  		if($newProspectList->$linkedField->_relationship->rhs_module == $thisReport->report_module)
	  		{
	  		 	$foundModule = true;
	  		}
	  	}
	 
	    print ($foundModule) ? 'true' : 'false';

	  
	}
	
	function action_get_enum()
	{
		
	 	global $app_list_strings, $beanFiles, $beanList, $db;
	 	
	 	
	 	$pathArray = explode('::', $_REQUEST['path']);
	 	
	 	
	 	$fieldArray = explode(':',$pathArray[count($pathArray) - 1]);
	 	$moduleArray = explode(':',$pathArray[count($pathArray) - 2]);
	 	
	 	
	 	require_once($beanFiles[$beanList[$moduleArray[1]]]);
	 	$parentModule = new $beanList[$moduleArray[1]];
	 	
	 	if($moduleArray[0] == 'link')
	 	{
		 	
		 	$parentModule->load_relationship($moduleArray[2]);
		 	
		 	
		 	$thisModuleName = $parentModule->$moduleArray[2]->getRelatedModuleName();
		 	require_once($beanFiles[$beanList[$parentModule->$moduleArray[2]->getRelatedModuleName()]]);
		 	$thisModule = new $beanList[$parentModule->$moduleArray[2]->getRelatedModuleName()];	 	

		 	
		 	
	 		switch($thisModule->field_name_map[$fieldArray[1]]['type'])
	 		{
	 			case 'enum':
		 		 foreach($app_list_strings[$thisModule->field_name_map[$fieldArray[1]]['options']] as $value => $text)
				 	{
				 		$returnArray[] = array('value' => $value, 'text' => $text);
				 	}
			 	break;
	 			case 'user_name':
	 				$usersResult = $db->query('SELECT id, user_name FROM users WHERE deleted = \'0\' AND status = \'Active\'');
	 				while($userRecord = $db->fetchByAssoc($usersResult))
	 				{
	 					$returnArray[] = array('value' => $userRecord['user_name'], 'text' => $userRecord['user_name']);
	 				}
	 				break;	 				
	 			case 'assigned_user_name': 
	 				$usersResult = $db->query('SELECT id, user_name FROM users WHERE deleted = \'0\' AND status = \'Active\'');
	 				while($userRecord = $db->fetchByAssoc($usersResult))
	 				{
	 					$returnArray[] = array('value' => $userRecord['id'], 'text' => $userRecord['user_name']);
	 				}
	 				break;
	 		}
		 	
	 	}
	 	else
	 	{
	 		
	 		switch($parentModule->field_name_map[$fieldArray[1]]['type'])
	 		{
	 			case 'enum':
		 		 foreach($app_list_strings[$parentModule->field_name_map[$fieldArray[1]]['options']] as $value => $text)
				 	{
				 		$returnArray[] = array('value' => $value, 'text' => $text);
				 	}
			 	break;
	 			case 'user_name':
	 			case 'assigned_user_name': 
	 				$usersResult = $db->query('SELECT id, user_name FROM users WHERE deleted = \'0\' AND status = \'Active\'');
	 				while($userRecord = $db->fetchByAssoc($usersResult))
	 				{
	 					$returnArray[] = array('value' => $userRecord['id'], 'text' => $userRecord['user_name']);
	 				}
	 				break;
	 		}
	 	}

	 	
	 	print json_encode_kinamu($returnArray);
	}
	
	
	function action_load_report(){
		global $_REQUEST, $db;
		
		require_once('modules/KReports/KReport.php');
		$thisReport = new KReport();
		$thisReport->retrieve($_REQUEST['requester']);
		
		
		if(isset($_REQUEST['whereConditions']))
		{
		  $thisReport->whereOverride = json_decode_kinamu( html_entity_decode_utf8($_REQUEST['whereConditions']));
		}
		
		$totalArray['count'] = $thisReport->getSelectionResults(array('start' => $_REQUEST['start'], 'limit' => $_REQUEST['limit']), isset($_REQUEST['snapshotid']) ? $_REQUEST['snapshotid'] : '0', true);
		$totalArray['records'] = $thisReport->getSelectionResults(array('start' => isset($_REQUEST['start']) ? $_REQUEST['start'] : 0 , 'limit' => isset($_REQUEST['limit']) ? $_REQUEST['limit'] : 0) , isset($_REQUEST['snapshotid']) ? $_REQUEST['snapshotid'] : '0', false);

		
		print json_encode_kinamu($totalArray);
	}
	
	function action_get_nodes(){
		
		global $_REQUEST, $beanFiles, $beanList; 
		
		$nodeArray = explode(':', $_REQUEST['node']);
		
		$returnArray = array();
		
		if($nodeArray[0] == 'root')
		{
			print json_encode_kinamu($this->buildNodeArray($nodeArray['1'], 'TREE'));
		}
		if($nodeArray[0] == 'link')
		{
			require_once($beanFiles[$beanList[$nodeArray['1']]]);
			$nodeModule = new $beanList[$nodeArray['1']];
			
			
			$nodeModule->load_relationship($nodeArray['2']);
			
			
			$returnJArray = json_encode_kinamu($this->buildNodeArray($nodeModule->$nodeArray['2']->getRelatedModuleName(), 'TREE'));
			
			print $returnJArray;
		}
	}
	
	
	function action_get_fields()
	{
		global $_REQUEST, $beanFiles, $beanList;
		
		$nodeArray = explode(':', $_REQUEST['nodeid']);
		
		$returnArray = array();
		
		if($nodeArray[0] == 'root')
		{
			$returnJson = json_encode($this->buildFieldArray($nodeArray['1']));
			
			
			print $returnJson;
			
		}
		if($nodeArray[0] == 'link')
		{
			require_once($beanFiles[$beanList[$nodeArray['1']]]);
			$nodeModule = new $beanList[$nodeArray['1']];
			
			
			$nodeModule->load_relationship($nodeArray['2']);
			
			$returnJArray = json_encode_kinamu($this->buildFieldArray($nodeModule->$nodeArray['2']->getRelatedModuleName()));
			
			print $returnJArray;
		}
	}
	
	function buildFieldArray($module){
		global $beanFiles, $beanList; 
		$returnArray = array();
		require_once('include/utils.php');
		require_once($beanFiles[$beanList[$module]]);
		$nodeModule = new $beanList[$module];
		foreach($nodeModule->field_name_map as $field_name => $field_defs)
		{
			if($field_defs['type'] != 'link' 
				&& $field_defs['type'] != 'relate' 
				&& (!isset($field_defs['source']) || (isset($field_defs['source']) &&  $field_defs['source'] != 'non-db')
					|| ((isset($field_defs['source']) && $field_defs['source'] == 'non-db' )
						&& $field_defs['type'] == 'kreporter')
					)
				)
			{
				$returnArray[] = array(
									'id' => 'field:' . $field_defs['name'],
									'text' => $field_defs['name'],
									
									'name' => (translate($field_defs['vname'],$module ) != '') ? translate($field_defs['vname'],$module ) : $field_defs['name'],
				                    'type' => ($field_defs['type'] == 'kreporter') ? $field_defs['report_data_type'] :  $field_defs['type'],
									'leaf' => true
							);
			}
		}
		return $returnArray;
		
	}
	
	
	function buildNodeArray($module, $requester){
		global $beanFiles, $beanList; 
		require_once('include/utils.php');
		require_once($beanFiles[$beanList[$module]]);
		$nodeModule = new $beanList[$module];
		foreach($nodeModule->field_name_map as $field_name => $field_defs)
		{
			if($field_defs['type'] == 'link')
			{
				$returnArray[] = array(
									'id' => 'link:' . $module . ':' . $field_name,
									'text' => translate($field_defs['vname'],$module),
									'leaf' => false
							);
			}
		}
		return $returnArray;
	}	
	
}
?>
